import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/CheckS")
public class CheckUsernameServlet extends HttpServlet {

    UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {
        // 从请求中获取用户名
        boolean exists=false;
        // 设置响应格式为JSON（参考网页7/8）
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");

        User user = userDao.getUserByName(username);// 根据用户名查询用户信息

        System.out.println("db:"+user);// 打印查询结果
        if (user!=null){// 用户名已存在
            exists = true;// 标记用户名已存在
        }

        // 返回JSON对象（例如：{ "exists": true }）
        PrintWriter out = response.getWriter();// 获取PrintWriter对象
        out.print("{\"exists\": " + exists + "}");// 输出JSON对象
        out.flush();// 刷新输出流
    }
}
